package com.example.easyscript.utils;


import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef;
import com.sun.jna.platform.win32.WinUser;

import java.awt.*;


public class JnaUtils {

    static public void printAll(){
        User32.INSTANCE.EnumWindows(new WinUser.WNDENUMPROC() {
            public boolean callback(WinDef.HWND hWnd, Pointer data) {
                WinDef.RECT r = new WinDef.RECT();
                User32.INSTANCE.GetWindowRect(hWnd, r);
                char[] buffer = new char[1024];
                User32.INSTANCE.GetWindowText(hWnd, buffer, buffer.length);
                String title = Native.toString(buffer);
                if(User32.INSTANCE.IsWindowVisible(hWnd)){
                    System.out.println("hwnd: " + hWnd + ", rect: " + r + ", title: " + title);

                }
                return true;
            }
        }, null);
    }

    static public Rectangle getRect(String windowName) {
        WinDef.RECT dimensionsOfWindow = new WinDef.RECT();
        WinDef.HWND parentWindow = User32.INSTANCE.FindWindow(null, windowName);
        if (parentWindow == null) {
            System.out.println("miss");
            return null;
        }
        User32.INSTANCE.GetWindowRect(parentWindow, dimensionsOfWindow);
        return dimensionsOfWindow.toRectangle();
    }

    static public Rectangle getScreenSize() {
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        //双屏乘2
        int screenWidth = screenSize.width*2;
        int screenHeight = screenSize.height;
        return new Rectangle(screenWidth, screenHeight);
    }

    //置顶
    static public void setTop(String windowName){
        WinDef.HWND parentWindow = User32.INSTANCE.FindWindow(null, windowName);
        if (parentWindow == null) {
            System.out.println("miss");
        }
        User32.INSTANCE.SetForegroundWindow(parentWindow);
    }

    //最小化
    static public void setMin(String windowName){
        WinDef.HWND parentWindow = User32.INSTANCE.FindWindow(null, windowName);
        if (parentWindow == null) {
            System.out.println("miss");
        }
        User32.INSTANCE.ShowWindow(parentWindow, 6); // 6 = SW_MINIMIZE
    }

    public static void main(String[] args) {
        printAll();
        setTop("Vite + Vue + TS - Google Chrome");
    }
}
